/**
 * Created by Administrator on 2015/8/5.
 */
'use strict';
var _o2oServiceApi = require('../common/o2oServiceApi');
var o2oServiceApi = new _o2oServiceApi;
var _ = require('underscore');
var F = require('../common/function');
var MUsers = require('../model/users.js');
var C = require('../config/index');
var imgRule = require('../common/imgRule.js');

//for o2o
exports.o2oProcessShopItem = function*(item) {
  if (item.district && item.address) {
    item.address = item.district[0].name + ' ' + item.district[1].name + ' ' + item.district[2].name + ' ' +
      item.address.replace(item.district[0].name, ' ').replace(item.district[1].name, ' ').replace(item.district[2].name, ' ');
  }
  if (item.loc) {
    item.lng = item.loc[0];
    item.lat = item.loc[1];
    delete item.loc;
  }
  item.shopid = item.id;
  delete item.id;
  if (item.name) {
    item.shopName = item.name;
    delete item.name;
  }
  item.grade = item.eAverage;
  delete item.eAverage;
  item.discount = item.discount > 0 ? 1 : 0;
  item.reservation = item.reservation > 0 ? 1 : 0;
  delete item.eCount;
  delete item.district;
  delete item.eTotal;
  delete item.categories;
  delete item.otherInfo;
  delete item.ts;
  delete item.createdAt;
  delete item.status;

  if (item.tel != undefined) {
    item.tel = yield this.o2oShopTelephonesSort(item.tel);
  }
  item.type = 10;//type 10店面
  return item;
};

exports.o2oProcessWareItem = function*(item) {
  item = yield this.o2oTranslateProperty(item);
  let record = item;
  if (record.shops) {
    item.shopName = record.shops[0].sName;
    item.shopid = record.shops[0].sid;
    delete item.shops;
  }
  if (item.grade) {
    item.grade = item.eAverage;
    delete item.eAverage;
  }
  //if(item.images){
  //    if(item.images.length>0){
  //        item.image=item.images[0];
  //    }
  //}
  //delete item.images;
  delete item.categories;
  delete item.district;
  delete item.status;
  delete item.eTotal;
  delete item.eCount;
  delete item.esTimate;
  delete item.eAverage;
  delete item.serviceGrade;
  delete item.decorationGrade;

  item.type = 11;//type 11项目
  return item;
};

exports.o2oTranslateProperty = function*(item) {
  item.wareid = item.id;
  delete item.id;
  item.discountPrice = item.price;
  delete item.price;
  item.wareName = item.name;
  delete item.name;
  return item;
};

exports.o2oShopTelephonesSort = function *(tel_arr) {
  let telarr = [];
  for (let one of tel_arr) {
    if (one.substring(0, 3) == '400') {
      telarr.push({phone400: one});
    } else if (one.substring(0, 1) == '1') {
      telarr.push({cellPhone: one});
    } else if (one != '') {
      telarr.push({phone: one});
    }
  }
  let arr_sort = ['phone', 'phone400', 'cellPhone'];
  let tel_sort_arr = [];
  for (let one of arr_sort) {
    for (let i in telarr) {
      if (telarr[i][one] === undefined) continue;
      tel_sort_arr.push(telarr[i][one]);
    }
  }
  return tel_sort_arr.join(';');
}

exports.o2oValidateUserPressiom = function*(userId, pressiomsArr) {
  let body = {userId: userId, permissions: pressiomsArr, act: 1};
  let checkUserPressiom = yield o2oServiceApi.post('user', 'checkMany', 1, body);
  if (checkUserPressiom.status == 200 && checkUserPressiom['result']['hasPermission']) {
    return {success: true};
  } else
    return {success: false, message: checkUserPressiom['message']['msg']};
};

exports.o2oGetWareDetailByWareId = function*(wareid) {
  let wareDetailData = {};
  let wareData = yield o2oServiceApi.post('ware', 'detail', 1, {id: wareid, act: 1});
  if ((parseInt(wareData['result']['error']) == 1 || wareData.status == 400)) {
    return {vendorid: 0, vendorName: '', categories: [], price: '', wareName: ''};
  } else {
    wareDetailData.vendorid = wareData['result']['vendorid'];
    wareDetailData.wareName = wareData['result']['name'];
    wareDetailData.categoryName = wareData['result']['categories'][wareData['result'].categories.length - 1].name;
    wareDetailData.categoryCode = wareData['result']['categories'][wareData['result'].categories.length - 1].code;
    wareDetailData.price = wareData['result']['price'];
    wareDetailData.wareImage = wareData['result']['images'][0];
    let vendorDetail = yield  o2oServiceApi.post('vendor', 'detail', 1, {
      id: parseInt(wareDetailData.vendorid),
      act: 1
    });
    if ((parseInt(vendorDetail['result']['error']) == 1 || vendorDetail.status == 400)) {
      wareDetailData.vendorName = '瓷肌';
    } else {
      wareDetailData.vendorName = vendorDetail['result']['name'];
    }
  }
  return wareDetailData;
};

//get order detail by order Id
exports.o2oGetOrderDetailByOrderId = function*(body) {
  let orderDetailData = yield  o2oServiceApi.post('order', 'detail', 1, body);
  return orderDetailData;
};

//get ware detail by ware Id
exports.o2oGetWareInfoByWareId = function*(id) {
  let wareDetailData = yield  o2oServiceApi.post('ware', 'detail', 1, {act: 1, id: id});
  return wareDetailData;
};
//get shop detail by shop Id
exports.o2oGetShopInfoByShopId = function*(id) {
  let shopDetailData = yield o2oServiceApi.post('shop', 'detail', 1, {act: 1, id: parseInt(id)});
  return shopDetailData;
};
//get operation tags based on array
exports.o2oGetOperationTagsByArray = function*(tags_array) {
  let tags_detail_array = yield o2oServiceApi.post('category', 'list', 1, {act: 3, type: 3, codes: tags_array});
  if ((parseInt(tags_detail_array['result']['error']) == 1 || tags_detail_array.status == 400)) {
    return {};
  } else {
    tags_detail_array['result'] = _.filter(tags_detail_array['result'], function (record) {
      return record.level == 3;
    });
    return tags_detail_array['result'];
  }
}

//get order operations by order id
//status 0:未消费；1：已消费；2：已取消 3：退款中 4: 已退款；5已完成；6,未确认/代付款；
//Operation: 1 取消；2 付款；3 退款；4 取消退款 ；5 写美容日记；6更新美容日记
exports.o2oGetOrderOperation = function *(orderid, order) {
  let operationArray = [];
  if (order == undefined) {
    let orderBody = {act: 1, orderid: orderid};
    var orderData = yield  o2oServiceApi.post('order', 'detail', 1, orderBody);
    if (parseInt(orderData['result']['error']) == 1 || orderData.status == 400) {
      return operationArray;
    }
    order = orderData['result'];
  }
  switch (order.status) {
    case 0:
      operationArray.push(1, 2);//0未消费ȷ对应1取消；2付款
      break;
    case 1:
      operationArray.push(3);//1����ȷ�� /δ����/��ʹ��
      if (parseInt(order['refunding_number']) > 0) {
        operationArray.push(4);
      }
      if (parseInt(order['has_consumed_number']) > 0) {
        if (parseInt(order['daily_thread_id']) > 0) {
          operationArray.push(6);
        }
        else {
          operationArray.push(5);
        }
      }
      break;
    case 5://5�����
      if (parseInt(order['daily_thread_id']) > 0) {
        operationArray.push(6);
      }
      else {
        operationArray.push(5);
      }
    default:
      break;
  }
  //toDo ��ɾ��
  if (parseInt(order['daily_thread_id']) > 0) {
    operationArray.push(6);
  }
  return operationArray;
}

//save shop according to the shop object passed in
//save shop information
exports.o2oSaveShopInfo = function*(shopInfo) {
  let shopResult = yield  o2oServiceApi.post('shop', 'add', 1, shopInfo);
  return shopResult;
};

//get thread category based on the ware or tags which daily thread passed in
exports.o2oGetThreadCategory = function*(id) {
  let categoryResult = yield  o2oServiceApi.post('category', 'list', 1, {act: 3, type: 3, codes: [id]});
  if (categoryResult['result'].length == 0) {
    return 20;//�Ҳ���Ȧ�ӵ�ʱ�򷵻ػ���Ȧ�ӣ�Ĭ���ǻ���Ȧ��
  } else {
    if (categoryResult['result'][0].threadCategory && _.v.isInt(categoryResult['result'][0].threadCategory)) {
      return categoryResult['result'][0].threadCategory;
    }
  }
};


//get user permission detail based on uid passed in
exports.o2oGetUserPressiomInfo = function*(uid) {
  let userResult = yield  o2oServiceApi.post('authority', 'userDetail', 1, {act: 1, uid: uid});
  return userResult;
};

//update user information, including mobile and name
exports.o2oUpdateUserInfo = function *(obj_user) {
  let userResult = {};
  if (obj_user.uid && (obj_user.name || obj_user.mobile)) {
    obj_user.act = 1;
    userResult = yield  o2oServiceApi.post('authority', 'updateUserInfo', 1, obj_user);
  }
  return userResult;
};

//validate mandatory vendor fields according to vendor
/*
 exports.validateVendorFields = function (obj,keys_array) {
 let obj_vendor = {error_msg: ''};
 for (let p of keys_array) {
 if (typeof ( obj [p]) != " function ") {
 obj_vendor[p]=obj[p];
 if (obj[p] == undefined||_.isEmpty(_.str.trim(obj[p]))) {
 obj_vendor.error_msg += p + ' is undefined or empty,';
 } else if (_.v.isIn(p, ['disCodes', 'images'])) {
 if (!_.isArray(obj[p])) {
 obj_vendor.error_msg += p + ' is not an array,';
 }
 }else if(_.v.isIn(p,['licenseType','settled'])){//验证布尔值
 if(!_.v.isIn(parseInt(obj[p]),[0,1])){
 obj_vendor.error_msg += p + ' should be 0 or 1 only,';
 }
 }else if(_.v.isIn(p,['officerEmail'])){//验证Email地址
 if(!_.v.isEmail(obj[p])){
 obj_vendor.error_msg += p + ' is not a valid email address,';
 }
 }else if(_.v.isIn(p,['officerTel','financeTel','serviceTel'])){//验证是否为手机
 if(!_.v.isMobilePhone(obj[p],'zh-CN')){
 obj_vendor.error_msg += p + ' is not a valid mobile phone number,';
 }
 }
 }
 }
 if(obj_vendor.error_msg!=''){
 obj_vendor.error_msg +='please check.';
 }
 return obj_vendor;
 };*/

//validate mandatory organization fields according to organization
exports.validateOrganizationFields = function (obj, keys_array) {
  let obj_organization = {error_msg: ''};
  for (let p of keys_array) {
    if (typeof ( obj [p]) != " function ") {
      obj_organization[p] = obj[p];
      if (obj[p] == undefined || _.isEmpty(_.str.trim(obj[p]))) {
        obj_organization.error_msg += p + ' is undefined or empty,';
      } else if (_.v.isIn(p, ['status'])) {//验证布尔值
        if (!_.v.isIn(parseInt(obj[p]), [0, 1])) {
          obj_organization.error_msg += p + ' should be 0 or 1 only,';
        }
      } else if (_.v.isIn(p, ['shopKeeperEmail'])) {//验证Email地址
        if (!_.v.isEmail(obj[p])) {
          obj_organization.error_msg += p + ' is not a valid email address,';
        }
      } else if (_.v.isIn(p, ['shopKeeperTel'])) {//验证是否为手机
        if (!_.v.isMobilePhone(obj[p], 'zh-CN')) {
          obj_organization.error_msg += p + ' is not a valid mobile phone number,';
        }
      }
    }
  }
  if (obj_organization.error_msg != '') {
    obj_organization.error_msg += 'please check.';
  }
  return obj_organization;
};


//check permission whether includes the passed in permission code based on uid
exports.o2oCheckUserPermission = function *(uid, permission_array) {
  let userResult = {};
  if (obj_user.uid && (obj_user.name || obj_user.mobile)) {
    obj_user.act = 1;
    userResult = yield  o2oServiceApi.post('authority', 'updateUserInfo', 1, obj_user);
  }
  return userResult;
};

/**
 @todo 判断当前用户是否已登录
 函数名：o2oIsLogin
 * 参数：无
 * 返回：true,false
 */
exports.o2oIsLogin = function*(Env) {
  var fields = Env.I;
  let ip = Env.ip || '';//客户端ip
  var returnData = {
    status: false
  };
  var tokenKey = fields.tokenkey || '';
  if (tokenKey.length == 40) {
    var uid = yield F.redisCo.get('siss:user:token_' + tokenKey);
    if (uid != null && parseInt(uid) > 0) { // 如果已经在redis中存在
      var userInfo = yield F.redisCo.hmget('siss:user:uid_' + uid, ['uid', 'groupid', 'nickname', 'permissionCodes',
        'name', 'roleName', 'primary', 'vid', 'vendorType']);
      if (userInfo[0] == null || userInfo[1] == 5) {
        return returnData;
      }
      returnData.status = true;
      returnData.uid = parseInt(userInfo[0]);
      returnData.groupid = parseInt(userInfo[1]);
      returnData.nickname = userInfo[2];
      returnData.permissionCodes = userInfo[3];
      returnData.name = userInfo[4];
      returnData.roleName = userInfo[5];
      returnData.primary = parseInt(userInfo[6]);
      returnData.vid = parseInt(userInfo[7]);
      returnData.vendorType = parseInt(userInfo[8]);
      F.redisClient.expire('siss:user:token_' + tokenKey, C.session.ttl);
      F.redisClient.expire('siss:user:uid_' + userInfo[0], C.session.ttl);
    } else { //在redis中不存在
      var tokenKeyExp = parseInt(C.user.tokenKeyExp);//单位天
      var tokenKeyExp = tokenKeyExp * 24 * 60 * 60;
      var userInfo = yield MUsers.getUser('uid,groupid,nickname,mobile', 'tokenkey=? AND tokenttl+ ' + tokenKeyExp + ' >UNIX_TIMESTAMP()', [tokenKey]);
      if (userInfo.length > 0 && userInfo[0].groupid != 5) { // gid=5 是禁止访问组

        F.redisClient.SETEX('siss:user:token_' + tokenKey, C.session.ttl, userInfo[0].uid);//保存会话
        F.redisClient.expire('siss:user:uid_' + userInfo[0].uid, C.session.ttl);
        returnData.status = true;
        returnData.uid = userInfo[0].uid;
        returnData.groupid = userInfo[0].groupid;
        returnData.nickname = userInfo[0].nickname;
        let Mongo_user_data = yield o2oServiceApi.post('authority', 'userDetail', 1, {act: 1, uid: userInfo[0]['uid']});
        //判断用户角色关联表
        if (parseInt(Mongo_user_data['result']['error']) == 1 || Mongo_user_data.status == 400) {
          returnData.status = false;
          returnData.error_msg = '你还没有绑定到管理后台';
        } else {
          if (Mongo_user_data['result']['userMobile'] != userInfo[0]['mobile']) {
            returnData.status = false;
            returnData.error_msg = '你还没有绑定到管理后台';
          }
        }
        //判断商家角色绑定表的记录是否有效
        if (returnData.status) {
          if (Mongo_user_data['result']['status'] != 1) {
            returnData.status = false;
            returnData.error_msg = '无效账户';
          }
        }
        //判断商家是否无效
        if (returnData.status) {
          let vendor_data = yield o2oServiceApi.post('vendor', 'detail', 1, {
            act: 1,
            id: Mongo_user_data['result']['vid']
          });
          if (!vendor_data || vendor_data['result']['status'] != 1) {
            returnData.status = false;
            returnData.error_msg = '无效账户';
          }
        }
        returnData.permissionCodes = Mongo_user_data['result']['permissionCodes'];
        returnData.name = Mongo_user_data['result']['name'];
        returnData.roleName = Mongo_user_data['result']['roleName'];
        returnData.primary = Mongo_user_data['result']['primary'];
        returnData.vid = Mongo_user_data['result']['vid'];
        returnData.vendorType = Mongo_user_data['result']['vendorType'];
      } else return returnData;
    }
  }
  return returnData;
};